package com.gylang.print.pdf.test.docx;

import org.docx4j.TraversalUtil;
import org.docx4j.finders.ClassFinder;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.ContentAccessor;
import org.docx4j.wml.Tbl;
import org.docx4j.wml.Tc;
import org.docx4j.wml.Tr;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author gylang
 * data 2021/6/2
 */
public class ReaderTableDoc {


	public static void main(String[] args) throws JAXBException {
		String template = SampleDoc.BASE + "table.docx";
		WordprocessingMLPackage wordMLPackage;
		try {
			wordMLPackage = WordprocessingMLPackage.load(new java.io.File(template));
			MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

			// 1. ClassFinder 构造类型查询器获取指定元素
			ClassFinder find = new ClassFinder(Tbl.class);
			new TraversalUtil(documentPart.getContent(), find);

			// 获取到的结果
			Tbl table = (Tbl) find.results.get(0);
			// 获取到第一个表格元素
			// 表格数据
			List<Object> trs = table.getContent();
			System.out.println(trs);
			System.out.println("=====================");

			for (Object obj : trs) {
				// 获取到tr
				Tr tr = (Tr) obj;
				List<Object> content = tr.getContent();
				System.out.println(content);
				// 获取所有的Tc元素
				List<Object> objList = getAllElementFromObject(tr, Tc.class);
				for (Object obj1 : objList) {
					Tc tc = (Tc) obj1;
					System.out.println(tc.getContent());
				}
				System.out.println("===============");
			}
		} catch (Docx4JException e) {
			e.printStackTrace();
		}
	}

	private static List<Object> getAllElementFromObject(Object obj, Class<?> toSearch) {
		List<Object> result = new ArrayList<>();
		if (obj instanceof JAXBElement)
			obj = ((JAXBElement<?>) obj).getValue();
		if (obj.getClass().equals(toSearch))
			result.add(obj);
		else if (obj instanceof ContentAccessor) {
			List<?> children = ((ContentAccessor) obj).getContent();
			for (Object child : children) {
				result.addAll(getAllElementFromObject(child, toSearch));
			}
		}
		return result;
	}
}
